/**
 * 
 */
package org.mips.Sirius.provider.SIRI;

import java.io.StringReader;
import java.util.ArrayList;

import org.mips.Sirius.components.Line;
import org.mips.Sirius.provider.ProviderException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

/**
 * @author mips
 * 
 */
public class SIRILinesDelivery {

	ArrayList<Line> lines;

	public SIRILinesDelivery(String xml) throws ProviderException {

		parse(xml);
	}

	public ArrayList<Line> getLines() {
		return lines;
	}

	private void parse(String xml) throws ProviderException {

		lines = new ArrayList<Line>();

		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();

			xpp.setInput(new StringReader(xml));
			int eventType = xpp.getEventType();

			String lineName = null;
			String lineRef = null;
			boolean openLineName = false;
			boolean openMonitored = false;
			boolean openLineRef = false;

			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					if (xpp.getName().equals("LineName")) {
						openLineName = true;
					} else if (xpp.getName().equals("LineRef")) {
						openLineRef = true;
					} else if (xpp.getName().equals("Monitored")) {
						openMonitored = true;
					}
				} else if (eventType == XmlPullParser.END_TAG) {
					if (xpp.getName().equals("LineName")) {
						openLineName = false;
					} else if (xpp.getName().equals("Monitored")) {
						openMonitored = false;
					} else if (xpp.getName().equals("LineRef")) {
						openLineRef = false;
					}
				} else if (eventType == XmlPullParser.TEXT) {
					if (openLineName) {
						lineName = xpp.getText();
					}
					if (openLineRef) {
						lineRef = xpp.getText();
					}
					if (openMonitored) {
						if (xpp.getText().equals("true")) {
							if (lineName != null && lineRef != null) {
								lines.add(new Line(lineRef, lineName));
							}
						}
					}
				}
				eventType = xpp.next();
			}
		} catch (Exception e) {
			throw new ProviderException(e, "Couldn't parse LinesDelivery");
		}

		Log.d("debug", "Found " + lines.size() + " monitored lines: " + lines);
	}
}
